import {stringUtils} from "../../utils/stringUtils";
import jQuery from 'jquery';

const SCENE_PATH_TEMPLATE = "${root}/resources/scene/config.json";

class SceneManager {
    constructor() {
        if(!SceneManager.instance) {
            this.scenceCollection = {};
            SceneManager.instance = this;
        }
        return SceneManager.instance;
    }

    getConfig(name, context) {
        let deferred = jQuery.Deferred();
        if (this.scenceCollection[name]) {
            //如果已经获取过了
            deferred.resolve({config: this.scenceCollection[name]});
        } else {
            this._loadSceneConfig(context)
                .done(() => {
                    deferred.resolve({config: this.scenceCollection[name]});
                });
        }
        return deferred.promise();
    }

    exists(name) {
        return !!this.scenceCollection[name];
    }

    _loadSceneConfig(context) {
        let deferred = jQuery.Deferred();
        let basePath = context._trimSlash();
        let configPath = stringUtils.applyTemplate(SCENE_PATH_TEMPLATE, {
            "root": basePath ? basePath : "/"
        });
        jQuery.getJSON(configPath)
            .done((config)=> {
                jQuery.each(config, (key, value)=> {
                    if(this.scenceCollection[key] === undefined) {
                        this.scenceCollection[key] = value;
                    }
                });
                deferred.resolve();
            });
        return deferred.promise();
    }
}

const sceneManager = new SceneManager();
export default sceneManager;